package com.yafeed.trade.service.stock.impl;

import com.alibaba.fastjson.JSONArray;
import com.yafeed.trade.common.http.HttpUtils;
import com.yafeed.trade.component.SinaUrl;
import com.yafeed.trade.dao.IndustryStockMapper;
import com.yafeed.trade.pojo.dto.stock.IndustryStockDto;
import com.yafeed.trade.service.stock.IndividualService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description: 个股相关操作
 * @author: yanghj
 * @time: 2020-12-13 23:01
 */

@Service
public class IndividualServiceImpl implements IndividualService {

    @Resource
    private IndustryStockMapper industryStockMapper;


    private SinaUrl sinaUrl;

    private HttpUtils httpUtils;

    /**
     * @param page         页码
     * @param num          数量
     * @param industryCode 行业编码
     * @return list
     */
    @Override
    public List<IndustryStockDto> fetchSinaIndustryStock(int page, int num, String industryCode) {
        String industryStock = sinaUrl.getIndustryStock();
        String url = String.format(industryStock, page, num, industryCode);
        JSONArray objects = httpUtils.get(url, JSONArray.class);
        if (objects.isEmpty()) {
            return new ArrayList<>();
        }
        return objects.stream().map(item -> {
            Map<String, Object> map = (Map<String, Object>) item;
            return IndustryStockDto.of(map);
        }).collect(Collectors.toList());
    }


    /**
     * <pre>
     *     保存行业下的个股
     * </pre>
     *
     * @param industryStockDtos 行业股票信息
     * @return int
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int saveIndustryStock(List<IndustryStockDto> industryStockDtos) {
        if (industryStockDtos.isEmpty()) {
            return 0;
        }
        for (IndustryStockDto stockDto : industryStockDtos) {
            industryStockMapper.insertSelective(stockDto.toIndustryStock());
        }
        return industryStockDtos.size();
    }


    @Autowired
    public void setSinaUrl(SinaUrl sinaUrl) {
        this.sinaUrl = sinaUrl;
    }

    @Autowired
    public void setHttpUtils(HttpUtils httpUtils) {
        this.httpUtils = httpUtils;
    }
}
